<template>
    <div class="content_container">
        <div class="left_container management">
            <div class="title_management">
                <h2>任务管理</h2>
            </div>
            <!-- 筛选 -->
            <div class="content_management">
                <div class="select_management">
                    <div class="title">任务状态：</div>
                    <div class="content">
                        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable @change="changeStatus">
                            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="title">操作日期：</div>
                    <div class="content">
                        <el-date-picker v-model="queryParams.searchTimes" type="daterange" align="right" unlink-panels
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            :picker-options="pickerOptions" value-format="yyyy-MM-dd" @change="changeStatus">
                        </el-date-picker>
                    </div>
                    <div class="title">任务页面：</div>
                    <div class="content">
                        <el-select v-model="queryParams.pageCode" placeholder="请选择任务生成页面" clearable @change="changeStatus">
                            <el-option v-for="item in pageList" :key="item.pageCode" :label="item.name"
                                :value="item.pageCode">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="title">关键字查询：</div>
                    <div class="content">
                        <el-input v-model="queryParams.keyword" placeholder="任务名称/用户名" @input="querytaskName"
                            clearable></el-input>
                    </div>
                    <div class="control">
                        <el-button type="danger" size="small" :disabled="!Boolean(selectList.length)"
                            @click="deleteTask(selectList)">批量删除</el-button>
                    </div>

                </div>
                <!-- table -->
                <div class="table_management">
                    <el-table :data="tableData" style="width: 100%" border stripe :header-cell-style="getRowClass"
                        :max-height="maxHeight" v-loading="loading" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" align="center">
                        </el-table-column>
                        <el-table-column label="任务日期" prop="taskDate" align="center">
                        </el-table-column>
                        <el-table-column label="任务名称" prop="taskName" align="center">
                            <template slot-scope="scope">
                                <div class="taskName_dom">
                                    <span v-if="scope.row.taskStatus === '成功'" style="color:green"
                                        @click="jumpPage(scope.row)">{{ scope.row.taskName
                                        }}</span>
                                    <span v-else-if="scope.row.taskStatus === '失败'" style="color:red">{{ scope.row.taskName
                                    }}</span>
                                    <span v-else>{{ scope.row.taskName }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="任务状态" prop="taskStatus" align="center">
                        </el-table-column>
                        <el-table-column label="备注" prop="remark" align="center">
                        </el-table-column>
                        <el-table-column label="页面编码" prop="pageCode" align="center">
                        </el-table-column>
                        <el-table-column label="失败原因" align="center" width="200px" v-if="btnList.includes('error')">
                            <template slot-scope="scope">
                                <!-- v-copy="scope.row.error" -->
                                <el-button type="mini"  v-if="scope.row.error" @click="viewError(scope.row.taskName)">查看</el-button>
                                <el-button type="mini" v-copy="scope.row.error" v-if="scope.row.error">复制</el-button>
                                <!-- <div class="error">
                                    <el-tooltip placement="bottom">
                                        <div slot="content" v-html="errorReason(scope.row.error)"></div>
                                        <div class="error_dom">{{ scope.row.error }}</div>
                                    </el-tooltip>
                                    
                                </div> -->
                            </template>
                        </el-table-column>
                        <el-table-column label="创建用户" prop="userName" align="center">
                        </el-table-column>
                        <el-table-column label="操作" align="center" min-width="120px">
                            <template slot-scope="scope">
                                <el-tooltip class="item" effect="dark" content="终止任务" placement="top">
                                    <el-button size="mini" type="danger" icon="el-icon-remove-outline"
                                        @click="downloadDrawFile(scope.row.taskId)"
                                        v-if="scope.row.taskStatus == '进行中'"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="删除任务" placement="top">
                                    <el-button size="mini" type="danger" icon="el-icon-delete"
                                        @click="deleteTask([scope.row.taskId])"></el-button>
                                </el-tooltip>
                                <el-tooltip class="item" effect="dark" content="复制路径" placement="top">
                                    <el-button size="mini" type="info" icon="el-icon-s-check"
                                        v-if="btnList.includes('viewDrawTaskPath')" @click="copyPath(scope.row.taskId)"
                                        plain></el-button>
                                </el-tooltip>
                                <template v-if="scope.row.taskStatus == '失败'">
                                    <el-tooltip class="item" effect="dark" content="重新运行" placement="top">
                                        <el-button size="mini" type="warning" icon="el-icon-refresh"
                                            v-if="scope.row.runStatus && btnList.includes('rerun')" @click="rerun(scope.row)"></el-button>
                                        <el-button size="mini" type="warning" icon="el-icon-loading" v-if="!scope.row.runStatus && btnList.includes('rerun')"></el-button>
                                    </el-tooltip>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页器 -->
                    <div class="createDate">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="queryParams.pageNo" :page-sizes="[10, 20, 30, 40]"
                            :page-size="queryParams.pageSize" layout="->,total, sizes, prev, pager, next, jumper"
                            :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getTaskPageListRequest, removeDrawTaskRequest, stopTaskRequest } from '@/api/management'
import { pageSearchPersonTaskRequest, viewTaskPathRequest, reRunDrawTaskRequest } from '@/api/user'
import mixins from './mixins';
import { throttle } from '@/utils';
export default {
    mixins: [mixins],
    data() {
        return {
            btnList: this.$store.state.login.buttonPermissionList,
            total: 0,
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                taskStatus: null,   //任务状态
                searchTimes: null,     //操作日期
                pageCode: null,     //任务页面
                keyword: null,     //任务名称
            },
            //用户列表
            userList: [
                {
                    id: 0,
                    username: '1',
                }
            ],
            //任务状态
            statusList: [
                {
                    label: '失败',
                    value: -1
                },
                {
                    label: '进行中',
                    value: 0
                },
                {
                    label: '成功',
                    value: 1
                }
            ],
            pageList: [
                {
                    name: '1',      //页面名称
                    pageCode: '1',  //页面编码
                }
            ],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            tableData: [],
            selectList: [],
            running: true,
        }
    },
    created() {
        let id = this.$queryToObjectsearch(window.location.search)
        if (id) {
            this.queryParams.keyword = id.taskId
        }
        this.getList()
        this.init()
    },
    methods: {
        async init() {
            const res = await getTaskPageListRequest()
            if (res.code !== 200) return this.$message.error(res.message)
            this.pageList = res.data
        },
        async getList(queryParams) {
            const res = await pageSearchPersonTaskRequest(this.queryParams)
            if (res.code !== 200) return this.$message.error(res.message)
            this.tableData = res.data.list.map(item => {
                item.runStatus = true
                return item
            })
            this.total = res.data.total
            this.loading = false
        },
        //筛选
        querytaskName: throttle(function () {
            this.queryParams.pageNo = 1
            this.getList(this.queryParams)
        }, 500),
        //修改页数
        handleSizeChange(val) {
            this.queryParams.pageSize = val
            this.getList(this.queryParams)
        },
        //修改页码
        handleCurrentChange(val) {
            this.queryParams.pageNo = val
            this.getList(this.queryParams)
        },
        //终止任务
        downloadDrawFile(id) {
            this.$confirm('确定终止该任务吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        const res = await stopTaskRequest({ taskId: id })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                        this.getList()
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        //删除任务
        deleteTask(arr) {
            this.$confirm('确定删除该任务吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        console.log(arr);
                        const res = await removeDrawTaskRequest({ taskId: arr })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.getList()
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        handleSelectionChange(value) {
            this.selectList = value.map(item => item.taskId)
        },
        //失败原因
        errorReason(item) {
            if (item) {
                return item.replaceAll('\n', '<br>')
            } else {
                return '-'
            }
        },
        //复制地址
        async copyPath(taskId) {
            const res = await viewTaskPathRequest({ taskId })
            if (res.code !== 200) return this.$message.error(res.message)
            const textarea = document.createElement('textarea');
            textarea.value = res.data;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('Copy');
            document.body.removeChild(textarea);
            this.$message('复制成功！')
        },
        //重新运行
        async rerun(row) {
            row.runStatus = false
            const res = await reRunDrawTaskRequest({ taskId: row.taskId })
            if (res.code !== 200) {
                this.$message({
                    type: 'error',
                    message: this.errorReason(res.message),
                    dangerouslyUseHTMLString: true,
                })
            } else {
                this.$message({
                    type: 'success',
                    message: res.message
                })
            }
            row.runStatus = true
            this.getList()
        },
        changeStatus() {
            this.queryParams.pageNo = 1
            this.getList()
        },
        jumpPage(row) {
            let name = row.pageCode
            let taskId = row.taskId
            window.open(`${this.$url(window.location.origin)}/${name}?taskId=${taskId}`)
        },
        //查看报错信息
        viewError(id){
            window.open(`${this.$url(window.location.origin)}/scriptPage?taskName=${id}&page=management`)
        }
    }
}
</script>

<style lang="scss" scoped>
.title_management {
    margin-left: 30px;
}

.content_management {
    margin: 0 15px;

    .table_management {
        border: 1px solid #d3ddeb;
        border-radius: 6px;

        .createDate {
            padding-top: 15px;
        }
    }

    .select_management {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        line-height: 50px;
        margin-bottom: 15px;

        ::v-deep .el-input__inner {
            height: 35px;
            line-height: 35px;
            border-radius: 4px;
        }

        .title {
            margin-left: 10px;
        }

    }
}

.control {
    margin-left: 20px;
}

.error {
    display: flex;
    align-items: center;
    justify-content: space-around;

    .error_dom {
        width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

.taskName_dom {
    cursor: pointer;
}
</style>